<template>
  <GlobalDrawer v-model="visible" title="订单详情" size="80%" :show-footer-buttons="false">
    <div v-loading="loading" class="order-detail">
      <!-- 基础信息 -->
      <el-card header="基础信息" class="section">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ detail.order_no || '-' }}</el-descriptions-item>
          <el-descriptions-item label="订单类型">
            {{ getTypeLabel(detail.order_type || 0) }}
          </el-descriptions-item>
          <el-descriptions-item label="客户名称">
            {{ detail.customer_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="订单标题">{{ detail.title || '-' }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ detail.amount || 0 }}</el-descriptions-item>
          <el-descriptions-item label="合同编号">
            {{ detail.contract_no || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getStatusTagType(detail.status || 0)">
              {{ getStatusLabel(detail.status || 0) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="付款状态">
            <el-tag :type="getPaymentStatusTagType(detail.payment_status || 0)">
              {{ getPaymentStatusLabel(detail.payment_status || 0) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同状态">
            <el-tag :type="getContractStatusTagType(detail.contract_status || 0)">
              {{ getContractStatusLabel(detail.contract_status || 0) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建人">{{ detail.user_name || '-' }}</el-descriptions-item>
          <el-descriptions-item label="所属部门">
            {{ detail.dept_name || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ detail.create_time || '-' }}
          </el-descriptions-item>
          <el-descriptions-item label="订单描述" :span="2">
            {{ detail.description || '-' }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 付款记录 -->
      <el-card header="付款记录" class="section">
        <el-table :data="detail.payments || []" size="small">
          <el-table-column prop="payment_time" label="付款时间" width="140" />
          <el-table-column prop="amount" label="付款金额" width="100">
            <template #default="{ row }">¥{{ row.amount }}</template>
          </el-table-column>
          <el-table-column prop="payment_method" label="付款方式" width="100">
            <template #default="{ row }">
              {{ getPaymentMethodLabel(row.payment_method) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip />
          <el-table-column prop="create_time" label="创建时间" width="140" />
        </el-table>
      </el-card>

      <!-- 审核记录 -->
      <el-card header="审核记录" class="section">
        <el-table :data="detail.reviews || []" size="small">
          <el-table-column prop="review_type" label="审核类型" width="100">
            <template #default="{ row }">
              {{ getReviewTypeLabel(row.review_type) }}
            </template>
          </el-table-column>
          <el-table-column prop="review_status" label="审核结果" width="100">
            <template #default="{ row }">
              <el-tag :type="getReviewStatusTagType(row.review_status)">
                {{ getReviewStatusLabel(row.review_status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="reviewer_name" label="审核人" width="100" />
          <el-table-column
            prop="review_comment"
            label="审核意见"
            min-width="200"
            show-overflow-tooltip
          />
          <el-table-column prop="create_time" label="审核时间" width="140" />
        </el-table>
      </el-card>
    </div>
  </GlobalDrawer>
</template>

<script setup lang="ts">
  import { ref, watch, computed } from 'vue'
  import { orderApi } from '@/api/crm'
  import type { Order, Option, Payment, Review } from '@/types/crm'
  import GlobalDrawer from '@/components/common/GlobalDrawer.vue'

  // 扩展Order类型，包含payments和reviews
  interface OrderDetail extends Order {
    payments?: Payment[]
    reviews?: Review[]
    dept_name?: string
    customer_name?: string
    contract_no?: string
    order_no?: string
  }

  const props = defineProps({
    modelValue: {
      type: Boolean,
      default: false,
    },
    orderId: {
      type: Number,
      default: 0,
    },
  })

  const emit = defineEmits(['update:modelValue'])

  const visible = computed({
    get: () => props.modelValue,
    set: value => emit('update:modelValue', value),
  })

  const loading = ref(false)
  const detail = ref<Partial<OrderDetail>>({
    payments: [],
    reviews: [],
  })

  const typeOptions = ref<Option[]>([])
  const statusOptions = ref<Option[]>([])
  const paymentMethodOptions = ref<Option[]>([])

  // 获取订单详情
  const getOrderDetail = async () => {
    if (!props.orderId) return

    loading.value = true
    try {
      const res = await orderApi.detail(props.orderId)
      detail.value = res.data

      // 获取付款记录和审核记录
      const [paymentsRes, reviewsRes] = await Promise.all([
        orderApi.getPayments(props.orderId),
        orderApi.getReviews(props.orderId),
      ])

      detail.value.payments = paymentsRes.data
      detail.value.reviews = reviewsRes.data
    } catch (error) {
      console.error('获取订单详情失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 获取选项数据
  const getOptions = async () => {
    try {
      const [typeRes, statusRes, paymentMethodRes] = await Promise.all([
        orderApi.getOrderOptions(),
        orderApi.getStatusOptions(),
        orderApi.getPaymentMethodOptions(),
      ])
      typeOptions.value = typeRes.data
      statusOptions.value = statusRes.data
      paymentMethodOptions.value = paymentMethodRes.data
    } catch (error) {
      console.error('获取选项失败:', error)
    }
  }

  // 获取类型标签
  const getTypeLabel = (value: number) => {
    const option = typeOptions.value.find(item => item.value === value)
    return option ? option.label : '-'
  }

  // 获取状态标签
  const getStatusLabel = (value: number) => {
    const option = statusOptions.value.find(item => item.value === value)
    return option ? option.label : '-'
  }

  // 获取状态标签类型
  const getStatusTagType = (value: number) => {
    const types = ['', 'warning', 'info', 'primary', 'success', 'danger']
    return types[value] || 'info'
  }

  // 获取付款状态标签
  const getPaymentStatusLabel = (value: number) => {
    const labels = ['', '未付款', '已付款', '部分付款']
    return labels[value] || '-'
  }

  // 获取付款状态标签类型
  const getPaymentStatusTagType = (value: number) => {
    const types = ['', 'danger', 'success', 'warning']
    return types[value] || 'info'
  }

  // 获取合同状态标签
  const getContractStatusLabel = (value: number) => {
    const labels = ['', '未签署', '已签署', '已回收']
    return labels[value] || '-'
  }

  // 获取合同状态标签类型
  const getContractStatusTagType = (value: number) => {
    const types = ['', 'danger', 'warning', 'success']
    return types[value] || 'info'
  }

  // 获取付款方式标签
  const getPaymentMethodLabel = (value: number) => {
    const option = paymentMethodOptions.value.find(item => item.value === value)
    return option ? option.label : '-'
  }

  // 获取审核类型标签
  const getReviewTypeLabel = (value: number) => {
    const labels = ['', '到账审核', '合同回收审核']
    return labels[value] || '-'
  }

  // 获取审核状态标签
  const getReviewStatusLabel = (value: number) => {
    const labels = ['', '待审核', '通过', '驳回']
    return labels[value] || '-'
  }

  // 获取审核状态标签类型
  const getReviewStatusTagType = (value: number) => {
    const types = ['', 'warning', 'success', 'danger']
    return types[value] || 'info'
  }

  // 关闭对话框
  const handleClose = () => {
    visible.value = false
  }

  // 监听订单ID变化
  watch(
    () => props.orderId,
    newVal => {
      if (newVal) {
        getOrderDetail()
      }
    }
  )

  // 监听对话框显示状态
  watch(visible, newVal => {
    if (newVal && props.orderId) {
      getOrderDetail()
      getOptions()
    }
  })
</script>

<style scoped>
  .order-detail {
    padding-bottom: 20px;
  }

  .section {
    margin-bottom: 20px;
  }
</style>
